let storage = bui.storage();
let org;
let language;
let translate;
let zxEditor
loader.define(function (require, exports, module, global) {
    let pageview = {
        init() {
            translate = global.translate
            language = storage.get("language", 0)
            if (!language) {
                language = 'chinese_simplified'
            }

            try {
                translate.selectLanguageTag.show = false;
                let curLanguage = translate.language.getCurrent()
                if (curLanguage !== language) {
                    translate.changeLanguage(language)
                }
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
            if (language === "chinese_simplified") {
                router.$("#J_Form").css("font-size", "")
                router.$(".bui-input").css("font-size", "")
                router.$("#nameFb1").css("font-size", "")
            } else {
                router.$("#J_Form").css("font-size", ".22rem")
                router.$(".bui-input").css("font-size", ".22rem")
                router.$("#nameFb1").css("font-size", ".3rem")
            }

            let uiLoading = bui.loading({
                appendTo:"#fbGzhLoading",
                width: 40,
                height: 40,
                opacity: 0.5,
                text:"加载中。。。"
            });
            let uiLoadingBtn = bui.loading({
                appendTo:"#fbGzhLoading",
                width: 40,
                height: 40,
                opacity: 0.5,
                text:"提交中。。。"
            });
            uiLoading.show()

            router.$("#fbGzhFh").click(function () {
                router.replace({ url: "pages/fbZjGzh/fbZjGzh.html"});
            })

            org = storage.get("org",0)
            let token = storage.get("token", 0)
            let cateDo = storage.get("cateDo",0)
            router.$("#nameFb1").html("发布" +org.description + "信息")
            bui.ajax({
                url: global.api.verifyToken,
                method: "POST",
                headers: {Token: token}
            }).then(function(res) {
                if (res.code != '200') {
                    bui.confirm({
                        "title": "",
                        "height": 460,
                        "content": '<div class="bui-box-center"><div><h3>登录已过期</h3></div></div>',
                        "buttons": [{name: "确定", className: "primary-reverse"}],
                        callback: function () {
                            this.close();
                            storage.set("tzPage", 0)
                            router.replace({ url: "pages/mainIndex/mainIndex.html"});
                        }
                    });
                } else {
                    let user = res.data
                    let contentStatus = false, emailStatus = true, refreshcountStatus = true, titleStatus = true,linkStatus = false
                    // let titleStatus = false
                    let fixDateStr = ''
                    let fixDateStrZj = ''
                    let fix1DateStr = ''
                    let fix1DateStrZj = ''
                    let refreshtimeStr = ''
                    let refreshtimeStrZj = ''
                    let refreshcountZj = ''
                    let webSign = ''

                    if (user.userId != 1 && (!user.adminType || user.adminType == '1')) {
                        router.$('.glyqx').hide()
                        router.$('.glyqx1').hide()
                        router.$('.glyqx2').hide()

                        if (user.qxStr) {
                            if (user.qxStr.indexOf("2") > -1){
                                router.$('.glyqx').show()
                            }
                            if (user.qxStr.indexOf("3") > -1){
                                router.$('.glyqx1').show()
                            }
                            if (user.qxStr.indexOf("4") > -1){
                                router.$('.glyqx2').show()
                            }
                        }
                    } else {
                        router.$('.glyqx').show()
                        router.$('.glyqx1').show()
                        router.$('.glyqx2').show()
                    }

                    // 标题
                    let title = bui.input({
                        id: "#titleInput1",
                        showIcon: false,
                        onInput: function(e) {
                            if (e.target.value) {
                                if (e.target.value.length > 100) {
                                    titleStatus = false
                                    router.$("#titleTs").html("标题最多100个字")
                                    return false;
                                } else {
                                    titleStatus = true
                                    router.$("#titleTs").html("")
                                }
                            } else {
                                titleStatus = true
                                router.$("#titleTs").html("")
                                return false;
                            }
                            return true;
                        }
                    })
                    let email = bui.input({
                        id: "#emailInput4",
                        showIcon: false,
                        onInput: function(e) {
                            let rule = /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/
                            if (e.target.value) {
                                if (!rule.test(e.target.value)) {
                                    emailStatus = false
                                    router.$("#emailTs4").html("邮箱格式不对")
                                    return false;
                                } else {
                                    emailStatus = true
                                    router.$("#emailTs4").html("")
                                }
                            } else {
                                emailStatus = true
                                router.$("#emailTs4").html("")
                                return false;
                            }
                            return true;
                        }
                    })

                    zxEditor = new ZxEditor('#editorGzh', {
                        disableBackspaceDelete: false,
                        imageMaxSize: 5,
                        customPictureHandler:false,    //自定义图片处理，即不使用默认插入图片逻辑。
                        showToolbar: ['pic','text', 'link']
                    })
                    if (isWeiXin()) {
                        webSign = '1'
                        //获取微信配置
                        bui.ajax({
                            url: global.api.getWxConfig,
                            data: {url: location.href.split('#')[0]},
                            method: "GET"
                        }).then(function(res) {
                            if (res.code == '200') {
                                let dat = res.data

                                wx.config({
                                    debug: false,
                                    appId: dat.appId,
                                    timestamp: dat.timestamp,
                                    nonceStr: dat.nonceStr,
                                    signature: dat.signature,
                                    jsApiList: [
                                        // 所有要调用的 API 都要加到这个列表中
                                        'checkJsApi','chooseImage', 'previewImage', 'uploadImage', 'downloadImage','onMenuShareTimeline','chooseWXPay','getLocalImgData'
                                    ]
                                })
                                wx.ready(function () {
                                    // 自定义选择图片
                                    zxEditor.on('select-picture', next => {
                                        wx.chooseImage({//选择图片
                                            count: 9,//限制上传图片的张数
                                            success: function (res) {
                                                let localIds = res.localIds;
                                                if (localIds.length > 0) {
                                                    uiLoading.show()
                                                    photoUpload(localIds);
                                                } else {
                                                    bui.alert("未选择上传图片")
                                                }

                                                function photoUpload(localIds){//照片上传
                                                    let localId = localIds.splice(0, 1)[0];
                                                    //ios专用
                                                    if(localId.indexOf("wxlocalresource") != -1){
                                                        localId = localId.replace("wxlocalresource", "wxLocalResource");
                                                    }
                                                    //当不使用定时器的时候，连续上传1+照片后，会莫明其妙滴不再执行，迫不得已掏出定时器这个大杀器~
                                                    setTimeout(function(){
                                                        wx.uploadImage({//上传图片
                                                            localId: localId,
                                                            isShowProgressTips: 0,
                                                            success: function (res) {
                                                                let serverId = res.serverId
                                                                picShow(localId, serverId)
                                                                if(localIds.length >= 1){
                                                                    photoUpload(localIds);
                                                                }
                                                                if (localIds.length == 0) {
                                                                    uiLoading.stop()
                                                                }
                                                            }
                                                        })
                                                    },50);
                                                }

                                                function picShow(data, serverId) {
                                                    zxEditor.addImage(data, serverId);
                                                }
                                            }
                                        })
                                    })
                                })
                            }
                        })
                    } else {
                        let $fileInput = initFileInput()
                        // 自定义选择图片
                        zxEditor.on('select-picture', next => {
                            $fileInput.click();
                        })
                    }
                    //拖拽图片上传
                    zxEditor.addEvent(zxEditor.$content, 'drop', e=>{
                        e.preventDefault()
                        e.stopPropagation()
                        const items = e.dataTransfer.items;
                        for (let i = 0; i < items.length; i++) {
                            let item = items[i]
                            if ('text/html' === item.type) {
                                item.getAsString(str => {
                                    zxEditor.dialog.loading("加载中")
                                    disposePasteImg(str, global.api.imageAnalysisArticle).then((res) => {
                                        let srcReg2 = /src=[\'\"]?([^\'\"]*)[\'\"]?/i
                                        let img_src = res.match(srcReg2)[1];
                                        //正则把?x-oss-process后面的都去掉
                                        if (img_src) {
                                            img_src = img_src.replace(/\?.*/i, "");
                                            zxEditor.addImage(img_src)
                                        }
                                        zxEditor.dialog.removeLoading()
                                    });
                                })
                            }
                        }
                    })
                    zxEditor.addEvent(zxEditor.$content, 'paste', function (e) {
                        e.preventDefault();
                        let clipboardData = e.clipboardData
                        if (!clipboardData) return
                        let items = clipboardData.items
                        if (items) {
                            let len = items.length
                            let i, item;
                            for (i = 0; i < len; i++) {
                                item = items[i]
                                if (item.type === 'text/html') {
                                    item.getAsString(str => {
                                        if (str) {
                                            zxEditor.dialog.loading("加载中")
                                            let newStr = str
                                            if (str.indexOf("<!--StartFragment-->") > -1) {
                                                newStr = str.split('<!--StartFragment-->') [1].split('<!--EndFragment-->')[0]
                                            }
                                            disposePasteImg(newStr, global.api.imageAnalysisArticle).then((res) => {
                                                $(zxEditor.$content).append(res)
                                                zxEditor.dialog.removeLoading()
                                            });
                                        }
                                    })
                                } else if (item.type === 'text/plain' && len === 1) {
                                    item.getAsString(str => {
                                        _insertToContent(str);
                                    })
                                }
                            }
                        }
                    });
                    // 编辑器内容改变
                    zxEditor.on('change', function (type, zxeditor) {
                        let content = zxeditor.getContent()
                        if (content !== '<p><br></p>') {
                            contentStatus = true
                            router.$("#contentTs").html('')
                        } else {
                            contentStatus = false
                            router.$("#contentTs").html('内容不可为空')
                        }
                    })
                    zxEditor.on('add-link', next => {
                        router.$("#linkTitle").val('')
                        router.$("#link").val('')
                        linkStatus = false
                        alterLinkDialog.open()
                    })
                    // 链接
                    let link = bui.input({
                        id: "#linkInput",
                        showIcon: false,
                        onInput: function(e) {
                            let rule = /https?:\/\/[a-z0-9](\.[a-z0-9])*(\/[-a-z0-9_:@&?=+,.!/~*'%$])*/ig
                            if (e.target.value) {
                                if (!rule.test(e.target.value)) {
                                    linkStatus = false
                                    router.$("#linkTs").html("链接必须以(http(s))开头")
                                    return false;
                                } else {
                                    linkStatus = true
                                    router.$("#linkTs").html("")
                                }
                            } else {
                                linkStatus = false
                                router.$("#linkTs").html("链接不可为空")
                                return false;
                            }

                            return true;
                        }
                    })
                    // 自定义居中弹出框
                    let alterLinkDialog = bui.dialog({
                        id: "#alterLinkDialog",
                        height: 300,
                        // mask: false,
                        callback: function(e) {
                            let cla = router.$(e.target).attr('class')
                            if (cla.indexOf('blue') > -1) {
                                if (linkStatus) {
                                    zxEditor.addLink(link.value(), router.$("#linkTitle").val())
                                    this.close();
                                } else {
                                    bui.confirm({
                                        "title": "",
                                        "height": 460,
                                        "content": '<div class="bui-box-center"><div><h3>链接为空，或者不符合规则</h3></div></div>',
                                        "buttons": [{ name: "确定", className: "primary-reverse" }],
                                        callback:function(){
                                            this.close();
                                        }
                                    });
                                }
                            }
                        }
                    });

                    let refreshcount = bui.input({
                        id: "#refreshcountInput",
                        showIcon: false,
                        onInput: function(e) {
                            let rule = /^\d{0,10}?$/
                            if (e.target.value) {
                                if (!rule.test(e.target.value)) {
                                    refreshcountStatus = false
                                    router.$("#refreshcountTs").html("剩余刷新次数只能是整数最大99999999999次")
                                    return false;
                                } else {
                                    refreshcountStatus = true
                                    router.$("#refreshcountTs").html("")
                                }
                            } else {
                                refreshcountStatus = true
                                router.$("#refreshcountTs").html("")
                                return false;
                            }
                            return true;
                        }
                    })

                    let fix = bui.pickerdate({
                        handle: "#datepicker_input_fix",
                        bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                        // input 显示的日期格式
                        formatValue: "yyyy-MM-dd hh:mm:ss",
                        callback: function(e) {
                            fixDateStr = this.value()
                        }
                        // 如果不需要按钮,设置为空
                        // buttons: [{name:"取消"}]
                    });
                    fix.empty()
                    let fix1 = bui.pickerdate({
                        handle: "#datepicker_input_fix1",
                        bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                        // input 显示的日期格式
                        formatValue: "yyyy-MM-dd hh:mm:ss",
                        callback: function(e) {
                            fix1DateStr = this.value()
                        }
                        // 如果不需要按钮,设置为空
                        // buttons: [{name:"取消"}]
                    });
                    fix1.empty()
                    let refreshtime = bui.pickerdate({
                        handle: "#datepicker_input_refreshtime",
                        bindValue: true, // 1.5.3 新增, 修改的值会自动绑定到 handle, 不再需要自己去绑定
                        // input 显示的日期格式
                        formatValue: "hh:mm:ss",
                        callback: function(e) {
                            refreshtimeStr = this.value()
                        }
                        // 如果不需要按钮,设置为空
                        // buttons: [{name:"取消"}]
                    });
                    refreshtime.cols({
                        year: "none",
                        month: "none",
                        date: "none",
                    })
                    refreshtime.empty()

                    router.$("input[name='isFix']").change(function () {
                        if (router.$(this).val() == '1') {
                            if (fixDateStrZj) {
                                fixDateStr = fixDateStrZj
                            }
                            router.$("#fixDateK").show()
                        } else {
                            fixDateStrZj = fixDateStr
                            fixDateStr = ""
                            router.$("#fixDateK").hide()
                        }
                    })
                    router.$("input[name='isFix1']").change(function () {
                        if (router.$(this).val() == '1') {
                            if (fix1DateStrZj) {
                                fix1DateStr = fix1DateStrZj
                            }
                            router.$("#fix1DateK").show()
                        } else {
                            fix1DateStrZj = fix1DateStr
                            fix1DateStr = ""
                            router.$("#fix1DateK").hide()
                        }
                    })
                    router.$("input[name='refresh']").change(function () {
                        if (router.$(this).val() == '1') {
                            if (refreshtimeStrZj) {
                                refreshtimeStr = refreshtimeStrZj
                            }
                            if (refreshcountZj) {
                                router.$("#refreshcount").val(refreshcountZj)
                            }
                            router.$(".refreshK").show()
                        } else {
                            refreshtimeStrZj = refreshtimeStr
                            refreshcountZj = router.$("#refreshcount").val()
                            refreshtimeStr = ""
                            router.$("#refreshcount").val("")
                            router.$(".refreshK").hide()
                        }
                    })
                    router.$("#fbArticle1").click(function () {
                        let context = zxEditor.getContent(true).trim()
                        let titleStr = title.value()
                        if (contentStatus && emailStatus && refreshcountStatus && titleStatus && (context.length > 0 || titleStr)) {
                            // bui.btn("#fbArticle1").submit(function(loading) {
                            uiLoadingBtn.show()
                                let title1 = ''
                                if (!titleStr && context) {
                                    title1 = context.substring(0,30)
                                }

                                bui.ajax({
                                    url: global.api.insertArticle,
                                    data: {title: titleStr, title1: title1,contentText: context,content: zxEditor.getContent(), cityId: org.id,city: org.name, country: org.pName, isreview: org.isreview, isduplicate: org.isduplicate,
                                        cate: cateDo.id, cate2: cateDo.parent, email: email.value(), wx: router.$("#wx1").val(), tel: router.$("#tel1").val(),isfix: router.$("input[name='isFix']:checked").val(),
                                        isfix1: router.$("input[name='isFix1']:checked").val(), refresh: router.$("input[name='refresh']:checked").val(),fixexpStr: fixDateStr, fixexpStr1: fix1DateStr,refreshtimeStr: refreshtimeStr,
                                        refreshcount: refreshcount.value(), webSign: webSign
                                    },
                                    method: "POST",
                                    headers: {Token: token}
                                }).then(function(res){
                                    if (res.code == '200') {
                                        if(res.mSign == '0') {
                                            // 修改数据
                                            bui.confirm("发布成功，请在主页查看！", function(e) {
                                                //this 是指点击的按钮
                                                let text = router.$(e.target).text();

                                                if (text == "确定") {
                                                    storage.set("tzPage", 0)
                                                    router.replace({ url: "pages/mainIndex/mainIndex.html"});
                                                }
                                                this.close()
                                            });
                                        } else {
                                            bui.confirm({
                                                "title": "",
                                                "height": 460,
                                                "content": '<div class="bui-box-center"><div><img src="'+res.qrcode+'" width="70px" height="70px"><p>发布成功，可扫码联系管理员审核！</p></div></div>',
                                                "buttons": ["取消","确定"],
                                                callback: function(e) {
                                                    //this 是指点击的按钮
                                                    let text = router.$(e.target).text();

                                                    if (text == "确定") {
                                                        storage.set("tzPage", 0)
                                                        router.replace({ url: "pages/mainIndex/mainIndex.html"});
                                                    }
                                                    this.close()
                                                }
                                            });
                                        }
                                    } else {
                                        bui.alert("发布失败！")
                                    }
                                    // loading.stop()
                                    uiLoadingBtn.stop()
                                })
                            // })
                        } else {
                            if (!contentStatus) {
                                router.$("#contentTs").html('内容不可为空')
                            }
                            if (contentStatus && context.length === 0 && !titleStr) {
                                bui.alert("内容如果不包含文字则必须填写标题！")
                            } else {
                                bui.alert("数据不符合格式，请检查！")
                            }
                        }
                    })
                }
                uiLoading.stop()
            })
            try {
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
        }
    };

    // 初始化
    pageview.init();

    // 输出模块
    return pageview;
})

function isWeiXin() {
    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true
    } else {
        return false
    }
}

function isMobile() {
    let info = navigator.userAgent;
    //通过正则表达式的test方法判断是否包含“Mobile”字符串
    let isPhone = /mobile/i.test(info);
    //如果包含“Mobile”（是手机设备）则返回true
    return isPhone;
}

// 处理粘贴的图片，传递的参数是粘贴来的数据
function disposePasteImg(pasteStr, url) {
    return new Promise(function (resolve) {
        // 用于计数图片数量
        let imgNum = 0;
        //匹配图片
        let imgReg = /<img.*?(?:>|\/>)/gi;
        let imgReg2 = /<img.*?(?:>|\/>)/;
        //匹配src属性
        let srcReg = new RegExp(/src=[\'\"]?([^\'\"]*)[\'\"]?/i,"g");
        let srcReg2 = /src=[\'\"]?([^\'\"]*)[\'\"]?/i

        if (imgReg2.test(pasteStr)) {
            // 提取图片连接
            pasteStr.replace(imgReg, function (txt) {
                console.log("txt：")
                console.log(txt)
                return txt.replace(srcReg, function (src) {
                    let img_src = src.match(srcReg2)[1];
                    //正则把?x-oss-process后面的都去掉
                    img_src = img_src.replace(/\?.*/i, "");
                    // 查找到一个图片地址就讲图片数量加1
                    imgNum++;

                    // console.log("img_src:", img_src)
                    if (img_src.indexOf('http:') > -1 || img_src.indexOf('https:') > -1) {
                        if (img_src.indexOf("/58Upload/article/") === -1) {
                            // 将图片转成图片文件对象并上传得到图片地址，传递的参数是图片地址
                            imgUrlSwitchBlob(img_src, url).then((res) => {
                                // console.log("得到的地址res", res);

                                /**
                                 * 得到图片地址进行替换并将替换之后的文本返回渲染
                                 */
                                // 图片地址进行替换
                                pasteStr = pasteStr.replace(img_src, res);
                                // 替换之后将图片数量减1
                                imgNum--;
                                // 只有图片数量变成0的时候才会进行返回
                                if (imgNum === 0) {
                                    // console.log("返回imgNum", imgNum,pasteStr)
                                    resolve(pasteStr);
                                }
                            });
                        } else {
                            imgNum--;
                            if (imgNum === 0) {
                                // console.log("返回imgNum", imgNum,pasteStr)
                                resolve(pasteStr);
                            }
                        }
                    }
                });
            });
        } else {
            resolve(pasteStr);
        }
    })
}

/**
 * @函数名称: 将图片地址转成文件对象
 * @返回值:图片地址
 * @描述: 接受的参数是图片的全地址路径，在函数中调用upPasteImg函数上传图片得到图片路径并返回
 * @其它: 使用Promise处理异步问题
 * @param {String} param 图片地址
 */
function imgUrlSwitchBlob(param, url) {
    return new Promise(function (resolve) {
        /**
         * @函数名称: 调用函数进行上传
         * @返回值: 得到的图片路径
         * @param {String} key 图片名称，包含后缀
         * @param {Object} blob 文件对象
         */
        bui.ajax({
            url: url,
            data: {fileUrl: param},
            method: "POST",
        }).then(function(res){
            if (res.code == '200') {
                resolve(res.data.image);
            } else {
                resolve('');
            }
        })
    });
}

/**
 * 初始化图片选择input[type=file]
 * @returns {*}
 */
function initFileInput() {
    let $input = zxEditor.createVdom({
        tag: 'input',
        attrs: {
            style: 'display: none',
            type: 'file',
            accept: 'image/*',
            multiple: 'multiple'
        }
    }); // 添加至文档流中

    zxEditor.$wrapper.appendChild($input); // 绑定change事件

    zxEditor.addEvent($input, 'change', fileInputChangeHandler); // 清除value，防止选中同一文件不触发change事件
    zxEditor.addEvent($input, 'click', function (e) {
        e.target.value = '';
    }); // 返回$input，模拟click[type=file]时使用
    return $input;
}
/**
 * input[file]选中文件后处理函数
 * @param e
 */
function fileInputChangeHandler(e) {
    let files = this.files; // 转数组
    let arr = zxEditor.slice(files);

    let all = arr.length
    let cur = 0
    if (all > 0) {
        zxEditor.dialog.loading("加载中")
        arr.forEach(file => {
            // 创建一个FileReader对象
            let reader = new FileReader();
            // 将图片文件读取为Data URL
            reader.readAsDataURL(file);
            // 监听文件加载完成事件
            reader.onload = function () {
                // 在这里进行下一步操作
                // 获取读取的图片文件的Data URL
                let dataURL = reader.result;
                // 将Data URL转换为base64字符串
                let base64String = "data:"+file.type+";base64," + dataURL.split(",")[1];
                uploadPic(base64String, file.type, file.size).then(res => {
                    cur++
                    if (cur >= all) {
                        zxEditor.dialog.removeLoading()
                    }
                })
            };
        })
    }
}
//上传图片
function uploadPic(base64, type, size) {
    return new Promise(function (resolve) {
        /**
         * @函数名称: 调用函数进行上传
         * @返回值: 得到的图片路径
         * @param {String} key 图片名称，包含后缀
         * @param {Object} blob 文件对象
         */
        bui.ajax({
            url: uploadPicUrl,
            data: {upfile: base64, type: type, size: size},
            method: "POST",
        }).then(function(res){
            if (res.state == 'SUCCESS') {
                zxEditor.addImage(res.url);
            }
            resolve('')
        })
    });
}
function _insertToContent(pasteStr) {
    if (!pasteStr) {
        zxEditor.dialog.alert('剪贴板无有效的文本内容');
    } else {
        // 去除html标签
        pasteStr = zxEditor.removeHtmlTags(pasteStr); // 创建文本节点

        let $paste = zxEditor.createVdom(pasteStr);

        zxEditor.insertElm($paste, 'text');

        let tmr = setTimeout(function (_) {
            zxEditor.checkCursorPosition();

            clearTimeout(tmr);
            tmr = null;
        }, 350);
    }
}

